<template>
  <el-dialog
    v-model="dialogVisible"
    :title="goodsForm.id ? '编辑商品' : '新增商品'"
    width="30%"
  >
    <el-form
      ref="formRef"
      :model="goodsForm"
      :rules="rules"
      label-width="100px"
      style="padding-right: 30px"
    >
      <el-form-item label="名称:" prop="name">
        <el-input v-model="goodsForm.name" placeholder="请输入名称"></el-input>
      </el-form-item>
      <el-form-item label="所属分类:" prop="subCategoryId">
        <SubCategorySelect v-model="goodsForm.subCategoryId" />
      </el-form-item>
      <el-form-item label="spu编码:" prop="spuCode">
        <el-input v-model="goodsForm.spuCode" placeholder="请输入spu编码"></el-input>
      </el-form-item>
      <el-form-item label="描述:" prop="desc">
        <el-input v-model="goodsForm.desc" placeholder="请输入描述"></el-input>
      </el-form-item>
      <el-form-item label="价格:" prop="price">
        <el-input v-model="goodsForm.price" placeholder="请输入价格"></el-input>
      </el-form-item>
      <el-form-item label="原价:" prop="oldPrice">
        <el-input v-model="goodsForm.oldPrice" placeholder="请输入原价"></el-input>
      </el-form-item>
      <el-form-item label="品牌:" prop="brand">
        <el-input v-model="goodsForm.brand" placeholder="请输入品牌"></el-input>
      </el-form-item>
      <el-form-item label="图片:" prop="picture">
        <ImgUpload @sendImage="sendImage" :initialImage="goodsForm.picture" />
      </el-form-item>
      <el-form-item
        v-for="(spec, index) in goodsForm.specList"
        :key="index"
        :label="'规格：' + (index + 1)"
      >
        <SpecSelect
          v-model="spec.id"
          :disabled="goodsForm.id"
          style="margin-right: 10px"
        />
        <el-button type="danger" @click="removeSpec(index)" v-if="!goodsForm.id">删除</el-button>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="addSpec" v-if="!goodsForm.id">新增规格</el-button>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="onSubmit">提交</el-button>
        <el-button @click="dialogVisible = false">取消</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref } from "vue";
import { ElMessage } from "element-plus";
import { addGoodsAPI, editGoodsAPI } from "@/apis/goods.js";
import ImgUpload from "@/components/ImageUpload/index.vue";
import SubCategorySelect from "./SubCategorySelect.vue";
import SpecSelect from "./SpecSelect.vue";

// 状态和引用定义
const dialogVisible = ref(false);
const formRef = ref(null);
const goodsForm = ref({
  name: "",
  subCategoryId: "",
  spuCode: "",
  desc: "",
  price: "",
  oldPrice: "",
  brand: "",
  picture: "",
  specList: [],
});

// 表单验证规则
const rules = {
  name: [
    { required: true, message: "名称不能为空", trigger: "blur" },
    { min: 2, max: 10, message: "名称为2-10个字符", trigger: "blur" },
  ],
  subCategoryId: [
    { required: true, message: "所属分类不能为空", trigger: "blur" },
  ],
  spuCode: [
    { required: true, message: "spu编码不能为空", trigger: "blur" },
    { min: 2, max: 10, message: "spu编码为2-10个字符", trigger: "blur" },
  ],
  desc: [{ required: true, message: "备注不能为空", trigger: "blur" }],
  price: [{ required: true, message: "价格不能为空", trigger: "blur" }],
  oldPrice: [{ required: true, message: "原价不能为空", trigger: "blur" }],
  brand: [
    { required: true, message: "品牌不能为空", trigger: "blur" },
    { min: 2, max: 10, message: "品牌为2-10个字符", trigger: "blur" },
  ],
  picture: [{ required: true, message: "图片不能为空", trigger: "blur" }],
};

// 事件定义
const emit = defineEmits(["success"]);

const addSpec = () => {
  if (!Array.isArray(goodsForm.value.specList)) {
    goodsForm.value.specList = [];
  }
  goodsForm.value.specList.push({ id: "" });
};

const removeSpec = (index) => {
  goodsForm.value.specList.splice(index, 1);
};

// 提交表单处理
const onSubmit = async () => {
  await formRef.value.validate();

  const specIds = goodsForm.value.specList.map((spec) => spec.id);

  const formData = {
    ...goodsForm.value,
    specIds,
  };
  const isEdit = goodsForm.value.id;
  if (isEdit) {
    await editGoodsAPI(formData);
    ElMessage.success("编辑成功");
  } else {
    await addGoodsAPI(formData);
    ElMessage.success("添加成功");
  }
  dialogVisible.value = false;
  emit("success", isEdit);
};

// 图片上传处理
const sendImage = (url) => {
  goodsForm.value.picture = url;
};

// 打开对话框并初始化数据
const open = (row) => {
  dialogVisible.value = true;
  goodsForm.value = { ...row };
};

// 暴露方法
defineExpose({
  open,
});
</script>